package com.jhgk.jhcee.auth.service.impl;

import com.jhgk.jhcee.common.constant.AuthConstant;
import com.jhgk.jhcee.auth.domain.model.SecurityUserModel;
import com.jhgk.jhcee.common.constant.MessageConstant;
import com.jhgk.jhcee.common.domain.UserModel;
import com.jhgk.jhcee.auth.service.SysUserInfoService;
import com.jhgk.jhcee.common.resultful.BasisResultful;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户管理业务类
 * Created by macro on 2020/6/19.
 */
@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    SysUserInfoService sysUserInfoService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String clientId = request.getParameter("client_id");
        UserModel userModel = new UserModel();
        if(AuthConstant.ADMIN_CLIENT_ID.equals(clientId)){
            BasisResultful<UserModel> userBasisResultful = sysUserInfoService.loadUserByUsername(username);
            userModel = userBasisResultful.getResult();
        }
        userModel.setClientId(clientId);
        SecurityUserModel securityUser = new SecurityUserModel(userModel);
        if (!securityUser.isEnabled()) {
            throw new DisabledException(MessageConstant.ACCOUNT_DISABLED);
        } else if (!securityUser.isAccountNonLocked()) {
            throw new LockedException(MessageConstant.ACCOUNT_LOCKED);
        } else if (!securityUser.isAccountNonExpired()) {
            throw new AccountExpiredException(MessageConstant.ACCOUNT_EXPIRED);
        } else if (!securityUser.isCredentialsNonExpired()) {
            throw new CredentialsExpiredException(MessageConstant.CREDENTIALS_EXPIRED);
        }
        return securityUser;
    }

}
